package com.codi.api.interceptor;

import com.codi.base.util.EqualsUtil;
import com.codi.bus.constant.GlobalConstant;
import com.codi.bus.core.jwt.Jwt;
import com.codi.bus.core.jwt.TokenState;
import com.codi.bus.core.resultModel.BaseResult;
import com.codi.bus.exception.BaseException;
import com.codi.goldlife.external.ExchangeServiceApi;
import com.codi.goldlife.external.databean.ResultBean;
import com.codi.message.constant.ErrorConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: zengxl
 * @Description:
 * @Date: 2018/3/12 9:30
 */
@Slf4j
public class GoldlifeValidateInterceptor implements HandlerInterceptor {
    @Autowired
    private ExchangeServiceApi exchangeServiceApi;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String token    = request.getHeader("token");
        String phone    = request.getHeader("phone");
        String userId    = request.getHeader("userId");
        if (StringUtils.isBlank(phone) || StringUtils.isBlank(token) || StringUtils.isBlank(userId)) {
            log.error("金品生活系统拦截器(GoldlifeValidateInterceptor)：请求头必须包含token、userid、phone");
            throw new BaseException(ErrorConstant.ERROR_INVALID_REQUEST, "非法请求,请求头缺少必要信息",GlobalConstant.ERROR_TYPE_BUSINESS);
        }
        ResultBean bean = exchangeServiceApi.validateToken(token, phone, userId);
        if (!bean.isSuccess()) {
            log.error("金品生活系统拦截器(GoldlifeValidateInterceptor)：{}",bean.getErrorMessage());
            throw new BaseException(ErrorConstant.ERROR_INVALID_REQUEST, bean.getErrorMessage(),GlobalConstant.ERROR_TYPE_BUSINESS);
        }else {
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
